﻿using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace ICodeShare.UI.Converters
{
    #region IValueConverter
    /// <summary>
    /// 日期转换类 DateTime转换成yyyy/MM/dd（年/月/日）格式
    /// </summary>
    /// <example>
    /// 1.在xmal文件引用DateConverter类所在命名空间。
    ///   xmlns:cvts="http://schemas.extended.wpf.com/converters"
    /// 2.在xaml文件添加Resources。
    ///   <Window.Resources>
    ///   <cvts:DateTimeToStringConverter x:Key="cvtsDateTimeToString"/>
    ///   </Window.Resources>
    /// 3.在xaml文件中指定Binding值的Converter
    ///   Text="{Binding CurrentDate, Converter={StaticResource cvtsDateTimeToString}}"
    /// </example>
    [ValueConversion(typeof(DateTime), typeof(string))]
    public sealed class DateTimeToStringConverter : IValueConverter
    {
        public DateTimeToStringConverter()
        {

        }
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strDateTimeFormat = "yyyyMMddHHmmss";
            if (value is DateTime)
            {
                ParseParameter(parameter, out strDateTimeFormat);
                return ((DateTime)value).ToString(strDateTimeFormat);
            }
            return DependencyProperty.UnsetValue;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is string)
            {
                string strValue = value as string;
                DateTime resultDateTime;
                if (DateTime.TryParse(strValue, out resultDateTime))
                {
                    return resultDateTime;
                }
            }
            return DependencyProperty.UnsetValue;
        }

        #region Methods 方法
        private void ParseParameter(object parameter, out string dateTimeFormat)
        {
            dateTimeFormat = "yyyyMMddHHmmss";
            var stringValue = parameter as string;
            if (string.IsNullOrWhiteSpace(stringValue))
                return;
            dateTimeFormat = stringValue;

        }
        #endregion
    }
    #endregion

}
